package com.ykq.dao;

import java.sql.*;

public class BaseDao {
    ResultSet rs = null;
    Connection conn = null;
    PreparedStatement ps = null;
    String url = "jdbc:mysql://localhost:3306/day1206";
    String username = "root";
    String password = "root";
    String driverName = "com.mysql.cj.jdbc.Driver";

    //增删改通用。
    public int edit(String sql, Object... params) {
        try {
            getConn();
            ps=conn.prepareStatement(sql);
            //为占位符赋值
            for(int i=0;i<params.length;i++){
                ps.setObject(i+1,params[i]);
            }
            int row=ps.executeUpdate();
            return row;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeAll();
        }
    }

    //获取连接对象
    public void getConn() throws Exception {
        Class.forName(driverName);
        conn = DriverManager.getConnection(url, username, password);
    }

    //关闭资源的方法
    public void closeAll() {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}














